import { reqlogin } from "../../http/api";
import { Toast } from "antd-mobile";
//state
const initState = {
  user: {
    phone: "",
    password: "",
  },

  // 2.1 初始化用户信息 userInfo
  userInfo: sessionStorage.getItem("userInfo")
    ? JSON.parse(sessionStorage.getItem("userInfo"))
    : {},
};

//action type
const TYPES = {
  LOGIN_CHANGEUSER: "LOGIN_CHANGEUSER",
  //userinfo type
  LOGIN_CHANGE_USERINFO: "LOGIN_CHANGE_USERINFO",
};

//reducer
const reducer = (state = initState, action) => {
  switch (action.type) {
    case TYPES.LOGIN_CHANGEUSER:
      return {
        ...state,
        user: {
          ...state.user,
          [action.key]: action.value,
        },
      };
    //   userInfo action={type:"LOGIN_CHANGE_USERINFO",userInfo:{}}
    case TYPES.LOGIN_CHANGE_USERINFO:
      return {
        ...state,
        userInfo: action.userInfo,
      };
    default:
      return state;
  }
};

//action creator
export const actions = {
  changeUser: (key, value) => ({
    type: TYPES.LOGIN_CHANGEUSER,
    key,
    value,
  }),
  //修改userInfo action
  changeUserInfo: (userInfo) => {
    if(userInfo.token){
        sessionStorage.setItem("userInfo",JSON.stringify(userInfo))
    }else{
        sessionStorage.removeItem("userInfo")
    }
    return { type: TYPES.LOGIN_CHANGE_USERINFO, userInfo: userInfo };
  },
  //登录的逻辑
  doLogin: (push) => {
    return (dispatch, getState) => {
      let user = getUser(getState());
     
      reqlogin(user).then(res => {
        if (res.data.code == 200) {
          Toast.show({
            content: res.data.msg,
          });
          dispatch(actions.changeUserInfo(res.data.list));
          push("/index/home");
        }
      });
    };
  },
};

//selector导出数据给组件
export const getUser = (state) => state.login.user;

export const getuserInfo = (state) => state.login.userInfo;
//导出reducer
export default reducer;
